<template>
  <div style="display: flex; flex-direction: column; height: 100%">
    <div class="app-container" v-if="getDetailData">
      <div class="app-container-inner display">
        <h4 class="h4_title">下载编码</h4>
        <div class="cards">
          <div class="card">
            <HPlainButton @click="codeBatchExcel(1)">
              <el-icon>
                <Download />
              </el-icon>
              XLSX格式下载
            </HPlainButton>
            <p class="tips">适用于Excel版本2007以上</p>
          </div>
          <div class="card">
            <HPlainButton @click="codeBatchExcel(2)">
              <el-icon>
                <Download />
              </el-icon>
              XLS格式下载
            </HPlainButton>
            <p class="tips">适用于Excel版本2003以上</p>
          </div>
          <div class="card">
            <HPlainButton @click="codeBatchExcel(3)">
              <el-icon>
                <Download />
              </el-icon>
              CSV格式下载
            </HPlainButton>
            <p class="tips">适用于Excel版本2007以下</p>
          </div>
          <div class="card">
            <HPlainButton @click="codeExportTxt">
              <el-icon>
                <Download />
              </el-icon>
              txt格式下载
            </HPlainButton>
          </div>
        </div>
      </div>

      <div class="app-container-inner">
        <div class="header">
          <div class="number">
            批次编码：<span>{{ getDetailData.code }}</span
            ><span v-if="getDetailData.type == 2">【配件编码】</span
            ><span v-else>【成品编码】</span>
          </div>
          <div class="text">
            <span>{{ getDetailData.createEmp }} 于{{ getDetailData.createTime }} 创建</span>
            <HPlainButton type="error" @click="deleCo">删除编码</HPlainButton>
          </div>
        </div>
      </div>
    </div>
    <div class="app-container" style="padding-top: 2px; height: 100%">
      <div class="app-container-inner" style="display: flex; flex-direction: column; flex: 1">
        <div class="btns change-all">
          <el-dropdown trigger="click">
            <HButton :disabled="selecttion.length == 0">
              批量操作
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </HButton>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="changeAll">
                  <el-icon>
                    <CircleCheck />
                  </el-icon>
                  批量修改
                </el-dropdown-item>
                <el-dropdown-item @click="deleteAll">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  批量删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="table" v-loading="loadingShow" element-loading-text="加载中...">
          <el-table
            :border="true"
            stripe
            resizable
            style="position: absolute"
            :data="bathList"
            @selection-change="handleChange"
            height="100%"
          >
            <el-table-column show-overflow-tooltip type="selection" width="40" />
            <el-table-column show-overflow-tooltip type="index" label="序号" width="50" />
            <el-table-column
              show-overflow-tooltip
              prop="securityCode"
              label="防伪编码"
              min-width="160"
            />
            <el-table-column
              show-overflow-tooltip
              prop="storeCode"
              label="仓储编码"
              min-width="160"
            />
            <el-table-column show-overflow-tooltip label="编码出入库状态" width="120">
              <template #default="scope">
                <HStatus type="warning" v-if="scope.row.storeStatus === 1">未出入库</HStatus>
                <HStatus type="success" v-if="scope.row.storeStatus === 2">已入库</HStatus>
                <HStatus type="success" v-if="scope.row.storeStatus === 3">已出库</HStatus>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="city" label="产品/配件名称" width="250">
              <template #default="scope">
                {{ scope.row.brand }}&nbsp;{{ scope.row.goodsModel }}&nbsp;{{
                  scope.row.goodsName
                }}&nbsp;{{ scope.row.goodsSpecName }}
              </template>
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="registerTime"
              label="登记时间"
              width="180"
            />
            <el-table-column label="状态" width="90">
              <template #default="scope">
                <HStatus type="info" v-if="scope.row.status === 3">已过保</HStatus>
                <HStatus v-if="scope.row.status === 2">质保中</HStatus>
                <HStatus type="info" v-if="scope.row.status === 1">未质保</HStatus>
                <HStatus type="error" v-if="scope.row.status === 4">已作废</HStatus>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="footer flex-justify-end">
          <div class="pagina">
            <Pagination
              ref="paginDom"
              :list_total="total"
              @size-change="getPageList"
              @current-change="getPageList"
            />
          </div>
        </div>

        <!-- 批量修改弹窗 -->
        <HModal v-model="changeDialog" title="批量修改编码" :width="550">
          <div class="change-dialog">
            <div class="header">
              编码数量：<span>{{ selecttion.length }}</span></div
            >
            <div class="table">
              <table>
                <colgroup>
                  <col width="120" />
                  <col width="120" />
                  <col width="80" />
                </colgroup>
                <thead>
                  <tr>
                    <th>商品型号</th>
                    <th>商品规格</th>
                    <th>质保周期</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>
                      <el-select
                        @change="changeSelect"
                        v-model="value1"
                        class="part"
                        placeholder="型号"
                        filterable
                        clearable
                        :loading="loading"
                        remote-show-suffix
                        :filter-method="remoteMethod"
                      >
                        <el-option
                          v-for="item in options"
                          :key="item.id"
                          :value="item.id"
                          :label="item.model"
                          class="left12"
                        />
                      </el-select>
                    </td>
                    <td>
                      <el-select
                        v-model="value2"
                        class="part"
                        placeholder="规格"
                        filterable
                        clearable
                        :loading="loading2"
                        remote-show-suffix
                        :filter-method="remoteMethod2"
                      >
                        <el-option
                          v-for="item in options2"
                          :key="item.id"
                          :value="item.id"
                          :label="item.name"
                          class="left12"
                        />
                      </el-select>
                    </td>
                    <td><el-input-number v-model="num" class="num-inp" :min="1" /></td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <template #footerRight>
            <HButton type="primary" is-modal @click="onSave">保存</HButton>
            <HButton is-modal @click="changeDialog = false">取消</HButton>
          </template>
        </HModal>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, onMounted, watch } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import moment from 'moment'
  import {
    codeBatchExportExcel,
    codeBatchExportTxt,
    getDetail,
    getbatchCodeList,
    deletebatchList,
    deleteCode,
    updateCodeGoods,
    productPageSelect,
    sparePageSelect,
    productSpecPageSelect,
    spareSpecPageSelect,
  } from '@/api/code'
  import _ from 'lodash'
  import { ArrowDown, CircleCheck, Delete, Download } from '@element-plus/icons-vue'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.snCode.batchDetail,
  })

  const router = useRouter()
  const route = useRoute()
  const value1 = ref(null)
  const value2 = ref(null)
  const num = ref(1)
  const total = ref(0)
  const paginDom = ref()
  const changeDialog = ref(false)
  const getDetailData = ref(null)
  const loading = ref(false)
  const loading2 = ref(false)
  const dataPage = ref({
    limit: 0,
    page: 0,
  })
  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val) => {
    selecttion.value = []
    val.forEach((item) => {
      selecttion.value.push({ id: item.id, tableType: item.tableType })
    })
  }
  const options = ref(null)
  const options2 = ref(null)
  // 批量修改
  const changeAll = () => {
    if (selecttion.value.length == 0) {
      ElMessage({
        message: '请选择要修改的编码',
        type: 'warning',
        offset: 400,
      })
      return
    }
    changeDialog.value = true
    remoteMethod('')
  }

  // 获取型号下拉选项的参数
  const getModelOptionsKeyword = ref({
    limit: 0,
    name: '',
    page: 0,
  })

  const remoteMethod = _.throttle((val: string) => {
    if (getModelOptionsKeyword.value.name !== val) {
      getModelOptionsKeyword.value.name = val
      getModelOptions()
    }
  }, 500)

  /**
   * 获取型号下拉选项
   */
  const getModelOptions = async () => {
    loading.value = true
    if (getDetailData.value.type === 1) {
      const res = await productPageSelect(getModelOptionsKeyword.value)
      if (res.data.code == 20000) {
        options.value = res.data.data.rows
        loading.value = false
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 3000,
          })
      }
    } else {
      const res = await sparePageSelect(getModelOptionsKeyword.value)
      if (res.data.code == 20000) {
        options.value = res.data.data.rows
        loading.value = false
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 3000,
          })
      }
    }
  }
  const changeSelect = () => {
    options2.value = []
    remoteMethod2('')
  }

  // 获取规格下拉选项的请求参数
  const getSpecificationsOptionsParam = ref({
    limit: 0,
    name: '',
    page: 0,
  })

  const remoteMethod2 = _.throttle((val: string) => {
    if (getSpecificationsOptionsParam.value.name !== val) {
      getSpecificationsOptionsParam.value.name = val
      getSpecificationsOptions()
    }
  }, 500)

  /**
   * 获取规格下拉选项
   */
  const getSpecificationsOptions = async () => {
    if (!value1.value) {
      return
    }
    loading2.value = true
    if (getDetailData.value.type === 1) {
      const res = await productSpecPageSelect(getSpecificationsOptionsParam.value, value1.value)
      if (res.data.code == 20000) {
        options2.value = res.data.data.rows
        loading2.value = false
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 3000,
        })
      }
    } else {
      const res = await spareSpecPageSelect(getSpecificationsOptionsParam.value, value1.value)
      if (res.data.code == 20000) {
        options2.value = res.data.data.rows
        loading2.value = false
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 3000,
        })
      }
    }
  }

  // 保存
  const onSave = () => {
    let data = {
      codes: selecttion.value,
      goodsId: value1.value,
      goodsSpecId: value2.value,
      type: getDetailData.value.type,
      warrantyDay: num.value,
    }
    updateCodeGoods(data).then((res) => {
      if (res.data.code == 20000) {
        getDetailData.value = res.data.data.row
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'success',
        })
        getDeta() // 详情
        getPageList() //编码列表
        changeDialog.value = false
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 4000,
        })
      }
    })
  }
  // 批量删除
  const deleteAll = () => {
    if (selecttion.value.length == 0) {
      ElMessage({
        message: '请选择要删除的编码',
        type: 'warning',
      })
      return
    }
    ElMessageBox.confirm('确认删除选中编码吗?', '提示', {
      draggable: true,
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      autofocus: false,
    }).then(() => {
      deleteCode(selecttion.value).then((res) => {
        if (res.data.code == 20000) {
          ElMessage({
            message: res.data.message,
            type: 'success',
            showClose: true,
          })
          getPageList() //编码列表
        } else {
          ElMessage({
            message: res.data.message,
            type: 'error',
            showClose: true,
          })
        }
      })
    })
  }
  // 删除编码
  const deleCo = () => {
    ElMessageBox.confirm('是否删除该编码?', '提示', {
      draggable: true,
      type: 'warning',
      cancelButtonText: '否',
      confirmButtonText: '是',
    }).then(() => {
      deletebatchList([getDetailData.value.id]).then((res) => {
        if (res.data.code == 20000) {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'success',
            duration: 4000,
          })
          router.push('/code/new')
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 4000,
          })
        }
      })
    })
  }
  const bathList = ref(null)
  const loadingShow = ref(true)
  // 详情
  const getDeta = async () => {
    const res = await getDetail(route.params.id)
    if (res.data.code == 20000) {
      getDetailData.value = res.data.data.row
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 4000,
      })
    }
  }
  //编码列表
  const getPageList = async () => {
    dataPage.value.limit = paginDom.value.size
    dataPage.value.page = paginDom.value.current
    const res = await getbatchCodeList(dataPage.value, route.params.id)
    total.value = parseInt(res.data.data.total) || 0
    bathList.value = res.data.data.rows
    loadingShow.value = false
  }
  // 下载Excel表格
  const codeBatchExcel = (val: number) => {
    // val======>  1-xlsx，2-xls，3-csv
    if (total.value != 0) {
      //没有数据时不能下载Excel
      codeBatchExportExcel(val, route.params.id).then((res) => {
        const url = window.URL.createObjectURL(
          new Blob([res.data], { type: val == 1 ? '.xlsx' : val == 2 ? '.xls' : '.csv' }),
        )
        const link = document.createElement('a')
        link.href = url
        link.download = `编码批次_${moment(new Date()).format('YYYYMMDD')}${
          val == 1 ? '.xlsx' : val == 2 ? '.xls' : '.csv'
        }`
        link.click()
      })
    }
  }
  // 下载txt
  const codeExportTxt = () => {
    if (total.value != 0) {
      //没有数据时不能下载Excel
      codeBatchExportTxt(route.params.id).then((res) => {
        const url = window.URL.createObjectURL(new Blob([res.data], { type: 'txt' }))
        const link = document.createElement('a')
        link.href = url
        link.download = `编码批次_${moment(new Date()).format('YYYYMMDD')}.txt`
        link.click()
      })
    }
  }

  watch(value1, (value) => {
    if (value) {
      getSpecificationsOptions()
    }
  })

  onMounted(async () => {
    await getDeta() // 详情
    await getPageList() //编码列表
    await getModelOptions() // 获取型号下拉选项
    await getSpecificationsOptions() // 获取规格下拉选项
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
